﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using CommandRunner.Contract;
using CommandRunner.Model;

namespace CommandRunner.WCFDataTransport
{
    [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
    public class CommandRunnerServer : ICommandRunnerServer
    {
        private List<CommandExecutionStatus> _finishedStatuses = new List<CommandExecutionStatus>() { CommandExecutionStatus.Failure, CommandExecutionStatus.Skipped, CommandExecutionStatus.Success };

        #region ICommandRunnerServer Members
        public Dictionary<Guid, CommandResult> Commands { get; set; }

        public CommandRunnerServer()
        {
            Commands = new Dictionary<Guid, CommandResult>();
        }

        public bool StartCommand(CommandResult commandResult)
        {
            ProcessCommand processCommand = new ProcessCommand(commandResult);

            Commands.Add(commandResult.CommandId, commandResult);
            processCommand.RunCommand();

            return true;
        }

        public bool IsCommandFinished(Guid commandId)
        {
            if (Commands.ContainsKey(commandId))
                return _finishedStatuses.Contains(Commands[commandId].Status);
            else
                return true;
        }

        public CommandResult GetCommandResult(Guid commandId)
        {
            if (IsCommandFinished(commandId))
            {
                CommandResult commandResult;
                if (Commands.ContainsKey(commandId))
                {
                    commandResult = Commands[commandId];
                    Commands.Remove(commandId);
                }
                else
                {
                    commandResult = new CommandResult()
                    {
                        CommandId = commandId, 
                        Output = "Command not registered with server", 
                        Status = CommandExecutionStatus.Failure
                    };
                }
                return commandResult;
            }
            return null;
        }
        #endregion
    }
}
